class Friendship < ActiveRecord::Base
  belongs_to :user
  has_one :friend, :class_name => 'User', :foreign_key => 'friend_id'
  
  validates_presence_of :user, :friend
  
  def after_create
    if user and friend
      user.update_attributes!(:friend_total => user.friend_tatal+1)
      friend.update_attributes!(:fans_total => friend.fans_total+1)
    end
  end
  
  private
  
  def validate
    errors.add_to_base("You cannot follow yourself") if user == friend 
    errors.add_to_base("You are already friends.") if Friendship.find_by_user_id_and_friend_id(user, friend)
  end
end
